package cn.tedu.service;

import cn.tedu.dao.CartMapper;
import cn.tedu.entity.Cart;
import cn.tedu.service.ex.DataNotFoundExcption;
import cn.tedu.service.ex.ServiceExcption;
import cn.tedu.service.port.CartService;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("cartService")
public class CartServiceImpl implements CartService {

    @Resource
    private CartMapper cartMapper;

    /**
     * 加入商品信息到购物车
     * @param cart  商品信息对象
     * @return      返回该商品id
     */
    public Integer add(Cart cart){
        // 先查询对应的数据
        Integer count = getRecordCount(
                cart.getUid(),
                cart.getGoodsId());
        // 判断该用户的购物车中是否已经有该商品
        if (count == 0) {
            // 该用户的购物车中尚无该商品
            // 则在购物中添加新数据
            Integer affectedRows
                    = cartMapper.insert(cart);
            if (affectedRows == 1) {
                return 1;
            } else {
                throw new ServiceExcption(
                        "将商品添加到购物车时出现未知错误，请联系管理员！");
            }
        } else {
            // 该用户的购物车已经有该商品
            // 则增加数量即可
            changeGoodsCount(
                    cart.getUid(),
                    cart.getGoodsId(),
                    cart.getGoodsCount());
            return 1;
        }
    }
    public Integer getRecordCount(Integer uid, Integer goodsId) {
        return cartMapper.getRecordCount(uid, goodsId);
    }

    public Integer changeGoodsCount(
            Integer uid,
            Integer goodsId,
            Integer amount) {
        Integer affectedRows =
                cartMapper.changeGoodsCount(
                        uid, goodsId, amount);
        if (affectedRows != 1) {
            throw new DataNotFoundExcption(
                    "购物车数据有误！请刷新后再次尝试！");
        }
        return affectedRows;
    }

    public List<Cart> getCartList(Integer uid) {
        return cartMapper.getCartList(uid);
    }

    /**
     * 根据id获取购物车的商品信息
     * @param id    购物车中的数据id
     * @param uid   用户id
     * @return      获取到的信息
     */
    public Cart getCartById(Integer id, Integer uid){
        return cartMapper.getCartById(id,uid);
    }
}
